<template>
  <div class="parent-page">
    <a-page-header title="家长管理" sub-title="查看和管理家长用户" />

    <a-card class="card-shadow">
      <!-- 搜索栏 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="关键词">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="姓名/手机号"
            style="width: 200px;"
          />
        </a-form-item>

        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" style="width: 120px;">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="ACTIVE">正常</a-select-option>
            <a-select-option value="DISABLED">禁用</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar
              :src="record.avatarUrl || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + record.id"
              :size="48"
            />
          </template>

          <template v-else-if="column.key === 'info'">
            <div>
              <div><strong>{{ record.realName || record.username }}</strong></div>
              <div style="color: #999; font-size: 12px;">{{ record.mobile }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'stats'">
            <a-space direction="vertical" :size="4">
              <span>需求: {{ record.demandCount || 0 }}</span>
              <span>订单: {{ record.orderCount || 0 }}</span>
            </a-space>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'ACTIVE' ? 'green' : 'red'">
              {{ record.status === 'ACTIVE' ? '正常' : '禁用' }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                详情
              </a-button>

            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 家长详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="家长详情"
      width="700px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="用户名">{{ currentParent.username }}</a-descriptions-item>
        <a-descriptions-item label="真实姓名">{{ currentParent.realName || '-' }}</a-descriptions-item>
        <a-descriptions-item label="手机号">{{ currentParent.mobile }}</a-descriptions-item>
        <a-descriptions-item label="邮箱">{{ currentParent.email || '-' }}</a-descriptions-item>
        <a-descriptions-item label="发布需求">{{ currentParent.demandCount || 0 }}</a-descriptions-item>
        <a-descriptions-item label="预约订单">{{ currentParent.orderCount || 0 }}</a-descriptions-item>
        <a-descriptions-item label="收藏教员">{{ currentParent.favoriteCount || 0 }}</a-descriptions-item>
        <a-descriptions-item label="评价次数">{{ currentParent.reviewCount || 0 }}</a-descriptions-item>
        <a-descriptions-item label="账号状态">
          <a-tag :color="currentParent.status === 'ACTIVE' ? 'green' : 'red'">
            {{ currentParent.status === 'ACTIVE' ? '正常' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="注册时间">
          {{ formatTime(currentParent.createdAt) }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { getAdminParentList, getParentDetail, updateParentStatus } from '@/api/parent'
import dayjs from 'dayjs'

const loading = ref(false)
const detailModalVisible = ref(false)
const currentParent = ref({})

const searchForm = reactive({
  keyword: '',
  status: ''
})

const columns = [
  { title: '头像', key: 'avatar', width: 80 },
  { title: '基本信息', key: 'info', width: 200 },
  { title: '统计数据', key: 'stats', width: 150 },
  { title: '收藏教员', dataIndex: 'favoriteCount', key: 'favoriteCount', width: 100 },
  { title: '评价次数', dataIndex: 'reviewCount', key: 'reviewCount', width: 100 },
  { title: '注册时间', dataIndex: 'createdAt', key: 'createdAt', width: 180 },
  { title: '状态', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150, fixed: 'right' }
]

const dataSource = ref([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const loadData = async () => {
  loading.value = true

  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }

    const res = await getAdminParentList(params)

    if (res.data) {
      dataSource.value = res.data.list || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: ''
  })
  pagination.current = 1
  loadData()
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

const handleView = async (record) => {
  try {
    const res = await getParentDetail(record.id)
    if (res.data) {
      currentParent.value = res.data
      detailModalVisible.value = true
    }
  } catch (error) {
    message.error('获取家长详情失败')
  }
}

const handleToggleStatus = (record) => {
  const newStatus = record.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'

  Modal.confirm({
    title: '确认操作',
    content: `确定要${statusText}家长 ${record.realName || record.username} 吗？`,
    onOk: async () => {
      try {
        await updateParentStatus(record.id, newStatus)
        record.status = newStatus
        message.success('状态更新成功')
      } catch (error) {
        message.error(error.message || '状态更新失败')
      }
    }
  })
}

const formatTime = (time) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.parent-page {
  .search-form {
    margin-bottom: 24px;
    padding-bottom: 24px;
    border-bottom: 1px solid #f0f0f0;
  }
}
</style>
